import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket();
        // 超时时间
        socket.setSoTimeout(3000);
        // 连接本地，端口2000；超时时间3000ms
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 2000), 3000);

        System.out.println("已发起服务器连接，并进入后续流程");
        System.out.println("客户端信息：" + socket.getLocalAddress() + " port" + socket.getLocalPort());
        System.out.println("服务器信息：" + socket.getInetAddress() + " port" + socket.getPort());
        try {
            todo(socket);
        }catch (Exception e){
            System.out.println("异常关闭");
        }

        socket.close();
    }

    private static void todo(Socket client) throws IOException{
        // 构建键盘输入流
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));

        // 得到socket输入流，并转换为打印流
        OutputStream outputStream = client.getOutputStream();
        PrintStream socketPrintStream = new PrintStream(outputStream);

        // 得到服务端输出流
        InputStream inputStream = client.getInputStream();
        BufferedReader sockerBufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        boolean flag = true;
        do {
            // 从键盘读一行
            String str = input.readLine();
            // 键盘输入数据发送给服务
            socketPrintStream.println(str);

            // 读取服务端返回的数据
            String echo = sockerBufferedReader.readLine();
            if ("bye".equalsIgnoreCase(echo)) {
                flag = false;
            }else {
                // 服务器数据打印到控制台
                System.out.println(echo);
            }
        }while (flag);

        socketPrintStream.close();
        sockerBufferedReader.close();
    }
}
